package com.zhilong.ui;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.TextView;

public class CountDownWidget extends TextView {
	private int count = 0;
	private int alertThreshold = 5;
	private CountDownTimer timer = null; 
	private CountDownListener cdListner = null;

	public CountDownWidget(Context context) {
		super(context);
		init(context);
	}
	
	public CountDownWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public void setCount(int count)
	{
		setCount(count, 5);
	}

	public void setCount(int count, int alertThreshold)
	{
		this.count = count;
		this.alertThreshold = alertThreshold;
		showCount(count);
	}

	private final void init(Context context)
	{
		this.setTextSize(48);
		this.setTextColor(android.graphics.Color.WHITE);
		this.setGravity(android.view.Gravity.RIGHT);
	}
	
	private void showCount(int count)
	{
    	 if(count <= alertThreshold)
    		setTextColor(android.graphics.Color.RED);
    	 else
     		setTextColor(android.graphics.Color.WHITE);
    	 
    	 setText("00:" + (count < 10 ? "0"+count : count));
	}
	
	public void restart()
	{
		stop();
		start();
	}
	
	public void start()
	{
		if(count <= 0)
			return;
		
		if(timer == null)
		{
			timer = new CountDownTimer(count*1000, 1000) {
	      	     public void onTick(long millisUntilFinished) {
	      	    	 showCount( (int)millisUntilFinished/1000 );
	      	     }
	
	      	     public void onFinish() {
	      	    	 showCount(0);
	      	    	 cdListner.onFinish();
	      	     }
      	  };
		}
      	
		timer.start();

	}
	
	public void stop()
	{
		if(timer != null)
		{
			timer.cancel();
			timer = null;
		}
	}
	
	public void setCountDownListener(CountDownListener listener)
	{
		this.cdListner = listener;
	}
	
	public abstract static class CountDownListener
	{
		abstract public void onFinish();
	}
}
